package com.ouyy.volunteerservice.volunteer.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    // 上传文件保存的目录（从 application.yml 读取）
    @Value("${file.upload-dir}")
    private String uploadDir;

    // 上传图片接口
    @PostMapping("/image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No file selected to upload");
        }

        try {
            // 获取文件名并拼接到上传目录
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            Path targetLocation = Paths.get(uploadDir).resolve(fileName);

            // ✅ 创建目录（如果不存在）
            Files.createDirectories(targetLocation.getParent());

            // 保存文件
            file.transferTo(targetLocation.toFile());

            return ResponseEntity.ok().body(fileName);
        } catch (IOException ex) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "File upload failed", ex);
        }
    }


    // 下载图片接口
    @GetMapping("/uploads/{filename}")
    @ResponseBody
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        try {
            // 解析文件路径
            Path filePath = Paths.get(uploadDir).resolve(filename).normalize();
            UrlResource resource = new UrlResource(filePath.toUri());

            // 确保文件存在
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG)  // 根据需要设置 MIME 类型
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}
